#include "gsmmsg.h"

#include <string>
#include <time.h>

#include "define.h"
#include "pfunc.h"

gsmmsg::gsmmsg() : readCount(3)
{
}

void gsmmsg::recvprint( char* data, int len)
{
	std::string text;
	for( int i=0;i<len; i++)
	{
		if( isprint( data[i] ))
		{
			text += data[i];
		}
	}
	printf("recv:%s\n", text.c_str());
}

//发送长消息
bool gsmmsg::sendmsg(const char* text, char *atres, char* exception, bool &wf,bool acssiif)
{
	if (strlen(text) <= 0)
	{
		sprintf(exception, "command is NULL");
		return false;
	}
	try {
		//printf("hex send[%d]:%s\n",strlen(text),text);
		char buf[256] = { 0 };
		int buflen = 0;
		if (acssiif)
		{
			memcpy(buf, text, strlen(text));
			buflen = static_cast<int>(strlen(text));
			printf("ascii send[%s]\n", buf);
		}
		else {
			buflen = pyfree::string2bytes((const char*)text, (unsigned char*)buf, static_cast<int>(strlen(text)));//hex to ascii
		}
		int rlen = Write((char*)buf, buflen);    // 先输出命令串 ascii
		if (rlen != buflen)
		{
			sprintf(exception,"ascii send[%d],but only succese[%d]:%s\n", buflen, rlen, buf);
			wf = false;
			return false;
		}
		wf = true;
		int  nrecs = 0;
		int Ret = 0;
		int readlen = 0;
		//time_t tnow = 0;
		//AT命令
		//tnow = time(NULL);
		int readIndex = 1;
		memset(atres, 0x00, 256);
		while (strlen(atres) == 0)
		{
			if(readIndex>readCount)
			{
			////等待1秒
			//if ((tnow + 1) < time(NULL)) {
				sprintf(exception, "command-out-time");
				return false;
			}
			mssleep(readSleep);
			char cache[128] = { 0 };
			memset(cache, 0x00, 128);
			Ret = Read(cache, 128);   // 读应答数据 ascii,结尾字段丢失,明明有数据,却返回长度为0
			readlen = static_cast<int>(strlen(cache));
			nrecs = (Ret <  readlen ? readlen : Ret);
			//printf("ascii rec[%d]:%s\n",nrecs,cache );
			if (acssiif)
			{
				memcpy(atres, cache, nrecs);
			}
			else {
				nrecs = pyfree::bytes2string((const unsigned char*)cache, (char*)atres, nrecs);//ascii to hex
			}
			//printf("hex rec[%d]:%s\n",nrecs,atres );	
			readIndex += 1;
		}
		//printf("hex rec[%d]:%s\n", nrecs, atres);
		//recvprint(atres,nrecs);
		return true;
	}
	catch (const std::exception& e)
	{
		sprintf(exception, "command exe exception[%s]",e.what());
		return false;
	}
	catch (...)
	{
		sprintf(exception, "command exe exception");
		return false;
	}
}

void gsmmsg::setReadSleep(int _rc)
{
	readSleep = _rc;
}

void gsmmsg::setReadCount(int _rc)
{
	readCount = _rc;
}